package com.flow.framework.common.json.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer;
import com.flow.framework.common.enumeration.CodeEnum;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 自定义 code enum 序列化
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/2
 */
@Slf4j
@JacksonStdImpl
public class CodeEnumSerializer extends StdScalarSerializer<CodeEnum> implements ContextualSerializer {

    /**
     * 序列化时会先调用空构造创建实例并调用com.flow.framework.common.json.serializer.CodeEnumSerializer.createContextual
     * 创建实际用于序列化的对象，且不同枚举类都会分别只调用一次
     */
    public CodeEnumSerializer() {
        super(CodeEnum.class);
    }

    public CodeEnumSerializer(Class<CodeEnum> clazz) {
        super(clazz);
    }

    @Override
    public void serialize(CodeEnum value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        String code = value.getCode();
        if (null != code) {
            gen.writeString(code);
        } else {
            gen.writeNull();
        }
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        return new CodeEnumSerializer((Class<CodeEnum>) property.getType().getRawClass());
    }
}
